package com.example.cdpbookstore.service.impl;

import com.example.cdpbookstore.dao.BookDao;
import com.example.cdpbookstore.dao.impl.BookDaoImpl;
import com.example.cdpbookstore.pojo.entity.Book;
import com.example.cdpbookstore.service.BookService;

import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

public class BookServiceImpl implements BookService {
    private final BookDao bookDao = new BookDaoImpl();

    @Override
    public List<Book> list() {
        return bookDao.list().stream().peek(this::decorate).collect(Collectors.toList());
    }

    @Override
    public List<Book> list(Long id) {
        return bookDao.list(id).stream().peek(this::decorate).collect(Collectors.toList());
    }

    @Override
    public Book getById(Long id) {
        return decorate(bookDao.getById(id));
    }

    @Override
    public List<Book> search(String search) {
        return bookDao.search(search);
    }

    private Book decorate(Book book) {
        // 添加销量字段
        int salesVolume = bookDao.getSalesVolume(book.getId());
        book.setSalesVolume(salesVolume);

        // 添加折扣字段
        book.setDiscount(book.getCurrentPrice().divide(book.getOriginalPrice(), 2, RoundingMode.HALF_UP));
        return book;
    }
}
